<template>
  <div class="order-detail-page">
    <div v-loading="loading" class="order-container">
      <div v-if="order" class="order-content">
        <!-- 页面标题 -->
        <div class="page-header">
          <h2>订单详情</h2>
          <el-button @click="goBack">返回</el-button>
        </div>

        <!-- 订单状态 -->
        <div class="order-status-section">
          <div class="status-info">
            <el-icon :size="40" class="status-icon">
              <component :is="getStatusIcon(order.status)"/>
            </el-icon>
            <div class="status-text">
              <h3>{{ getStatusText(order.status) }}</h3>
              <p v-if="order.status === 1">请在24小时内完成支付</p>
              <p v-else-if="order.status === 2">商家正在准备发货</p>
              <p v-else-if="order.status === 3">商品正在配送中，请耐心等待</p>
              <p v-else-if="order.status === 4">感谢您的购买，欢迎再次光临</p>
              <p v-else-if="order.status === 5">订单已取消</p>
            </div>
          </div>
          <div class="status-actions">
            <el-button
                v-if="order.status === 1"
                type="primary"
                @click="payOrder"
            >
              立即支付
            </el-button>
            <el-button
                v-if="order.status === 1"
                @click="cancelOrder"
            >
              取消订单
            </el-button>
            <el-button
                v-if="order.status === 3"
                type="success"
                @click="confirmOrder"
            >
              确认收货
            </el-button>
          </div>
        </div>

        <!-- 物流信息 -->
        <div v-if="order.status >= 3 && order.trackingNumber" class="logistics-section">
          <div class="section-title">物流信息</div>
          <div class="logistics-info">
            <div class="logistics-item">
              <span class="label">物流公司：</span>
              <span>{{ order.logisticsCompany || '顺丰快递' }}</span>
            </div>
            <div class="logistics-item">
              <span class="label">运单号：</span>
              <span>{{ order.trackingNumber }}</span>
            </div>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="address-section">
          <div class="section-title">收货信息</div>
          <div class="address-info">
            <div class="address-item">
              <span class="label">收货人：</span>
              <span>{{ order.receiverName }}</span>
            </div>
            <div class="address-item">
              <span class="label">联系电话：</span>
              <span>{{ order.receiverPhone }}</span>
            </div>
            <div class="address-item">
              <span class="label">收货地址：</span>
              <span>{{ order.receiverAddress }}</span>
            </div>
          </div>
        </div>

        <!-- 商品信息 -->
        <div class="products-section">
          <div class="section-title">商品信息</div>
          <div class="products-list">
            <div v-if="order.orderItems && order.orderItems.length > 0">
              <div
                  v-for="item in order.orderItems"
                  :key="item.id"
                  class="product-item"
              >
                <div class="product-image" @click="goToProductDetail(item.productId)">
                  <el-image
                      :alt="item.productName"
                      :src="item.productImage || '/placeholder.jpg'"
                      fit="cover"
                  />
                </div>
                <div class="product-info">
                  <h4 class="product-name" @click="goToProductDetail(item.productId)">{{ item.productName }}</h4>
                  <div class="product-price">¥{{ formatPrice(item.unitPrice) }}</div>
                </div>
                <div class="product-quantity">
                  x{{ item.quantity }}
                </div>
                <div class="product-subtotal">
                  ¥{{ formatPrice(item.totalPrice || (item.unitPrice * item.quantity)) }}
                </div>
                <!-- 评论按钮 -->
                <div v-if="order.status === 4" class="product-actions">
                  <el-button
                      v-if="!commentStatusMap[item.productId]"
                      size="small"
                      type="primary"
                      @click="commentProduct(item.productId)"
                  >
                    评价
                  </el-button>
                  <el-tag v-else size="small" type="success">已评价</el-tag>
                </div>
              </div>
            </div>
            <div v-else class="no-products">
              <el-empty description="暂无商品信息"/>
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="order-info-section">
          <div class="section-title">订单信息</div>
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span>{{ order.orderNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">下单时间：</span>
              <span>{{ formatDateTime(order.createTime) }}</span>
            </div>
            <div v-if="order.payTime" class="info-item">
              <span class="label">支付时间：</span>
              <span>{{ formatDateTime(order.payTime) }}</span>
            </div>
            <div v-if="order.deliveryTime" class="info-item">
              <span class="label">发货时间：</span>
              <span>{{ formatDateTime(order.deliveryTime) }}</span>
            </div>
            <div v-if="order.receiveTime" class="info-item">
              <span class="label">收货时间：</span>
              <span>{{ formatDateTime(order.receiveTime) }}</span>
            </div>
            <div v-if="order.remark" class="info-item">
              <span class="label">订单备注：</span>
              <span>{{ order.remark }}</span>
            </div>
          </div>
        </div>

        <!-- 费用明细 -->
        <div class="amount-section">
          <div class="section-title">费用明细</div>
          <div class="amount-info">
            <div class="amount-item">
              <span>商品总价：</span>
              <span>¥{{ formatPrice(order.totalAmount) }}</span>
            </div>
            <div class="amount-item">
              <span>运费：</span>
              <span>¥0.00</span>
            </div>
            <div class="amount-total">
              <span>实付金额：</span>
              <span class="total-price">¥{{ formatPrice(order.totalAmount) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import {onActivated, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Box, Check, Clock, Close, Van} from '@element-plus/icons-vue'
import {cancelOrder as cancelOrderApi, confirmOrder as confirmOrderApi, getOrderDetail} from '@/api/order'
import {getOrderItemsCommentStatus} from '@/api/comment'
import {formatDateTime} from '@/utils'

// 路由相关
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const order = ref(null)
const commentStatusMap = ref({})


// 页面初始化
onMounted(() => {
  fetchOrderDetail()
})

// 组件激活时刷新评论状态（从评论页面返回时）
onActivated(() => {
  if (order.value && order.value.status === 4) {
    fetchCommentStatus(route.params.id)
  }
})

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    const orderId = route.params.id

    if (!orderId) {
      ElMessage.error('订单ID不存在')
      router.push('/order')
      return
    }

    console.log('获取订单详情，订单ID:', orderId)
    const response = await getOrderDetail(orderId)
    console.log('订单详情响应:', response)

    if (response.data) {
      order.value = response.data
      console.log('订单数据:', order.value)

      // 如果订单已完成，获取评论状态
      if (order.value.status === 4) {
        await fetchCommentStatus(orderId)
      }
    } else {
      ElMessage.error('订单数据为空')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error(error.response?.data?.message || '获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 获取评论状态
const fetchCommentStatus = async (orderId) => {
  try {
    const response = await getOrderItemsCommentStatus(orderId)
    commentStatusMap.value = response.data || {}
  } catch (error) {
    console.error('获取评论状态失败:', error)
    commentStatusMap.value = {}
  }
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    1: Clock,    // 待支付
    2: Box,      // 待发货
    3: Van,      // 待收货
    4: Check,    // 已完成
    5: Close     // 已取消
  }
  return iconMap[status] || Clock
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '等待付款',
    2: '等待发货',
    3: '等待收货',
    4: '交易完成',
    5: '交易取消'
  }
  return statusMap[status] || '未知状态'
}

// 支付订单
const payOrder = () => {
  // 跳转到支付页面
  router.push({
    path: `/payment/${order.value.id}`,
    query: {
      orderNo: order.value.orderNo,
      totalAmount: order.value.totalAmount
    }
  })
}

// 取消订单
const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await cancelOrderApi(order.value.id, '用户取消订单')
    ElMessage.success('订单已取消')
    await fetchOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 确认收货
const confirmOrder = async () => {
  try {
    await ElMessageBox.confirm('确定已收到商品吗？', '确认收货', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'info'
    })

    await confirmOrderApi(order.value.id)
    ElMessage.success('确认收货成功')
    await fetchOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 评价单个商品
const commentProduct = (productId) => {
  // 跳转到单个商品评价页面
  router.push({
    path: '/comment/create',
    query: {
      orderId: order.value.id,
      productId: productId
    }
  })
}

// 评价功能已整合到单个商品评价中

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return '0.00'
  }
  return parseFloat(price).toFixed(2)
}
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem 0;
}

.order-container {
  max-width: 1200px;
  margin: 0 auto;
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--border-light);
  background: var(--bg-secondary);
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.order-content {
  padding: 2rem;
}

.section-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid var(--border-light);
}

/* 订单状态样式 */
.order-status-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
  background: linear-gradient(135deg, #409eff 0%, #36cfc9 100%);
  border-radius: 8px;
  color: white;
  margin-bottom: 30px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.status-icon {
  color: white;
}

.status-text h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.status-text p {
  margin: 0;
  opacity: 0.9;
}

.status-actions {
  display: flex;
  gap: 15px;
}

/* 其他区域样式 */
.logistics-section,
.address-section,
.products-section,
.order-info-section,
.amount-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.logistics-info,
.address-info,
.order-info {
  display: grid;
  gap: 15px;
}

.logistics-item,
.address-item,
.info-item {
  display: flex;
  align-items: center;
}

.label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

/* 商品列表样式 */
.products-list {
  display: grid;
  gap: 15px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.product-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.product-image:hover {
  opacity: 0.8;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-right: 15px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  cursor: pointer;
  transition: color 0.2s;
}

.product-name:hover {
  color: #409eff;
}

.product-price {
  color: #f56c6c;
  font-weight: 600;
}

.product-quantity {
  margin-right: 20px;
  color: #606266;
}

.product-subtotal {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

/* 费用明细样式 */
.amount-info {
  display: grid;
  gap: 10px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  color: #606266;
}

.amount-total {
  display: flex;
  justify-content: space-between;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.total-price {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-container {
    margin: 0 10px;
  }

  .order-content {
    padding: 20px;
  }

  .page-header {
    padding: 15px 20px;
  }

  .order-status-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
    padding: 20px;
  }

  .status-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .status-actions {
    width: 100%;
    justify-content: center;
  }

  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .label {
    width: auto;
    margin-right: 10px;
  }
}

/* 商品操作样式 */
.product-actions {
  margin-top: 8px;
}

.no-products {
  padding: 40px 0;
  text-align: center;
}
</style>
